package com.sprouting.personal.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 网络相关工具类
 *
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2022/11/21 9:44
 */
@Slf4j
public class NetTool {

    /**
     * 获取本地真正的IP地址，即获得有线或者无线WiFi地址
     * 过滤虚拟机、蓝牙等地址
     * 只要读取到了WiFi或者有线地址其中之一立即return
     * @return
     */
    public static String getLocalHostLANAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                // 去除回环接口，子接口，未运行和接口
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                }

                if (!netInterface.getDisplayName().contains("Intel") && !netInterface.getDisplayName().contains("Realtek")) {
                    continue;
                }
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = addresses.nextElement();
                    if (ip != null) {
                        // ipv4
                        if (ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
                break;
            }
        } catch (SocketException e) {
            log.error("获取主机ip地址时出错(Error when getting host ip address)", e);
        }
        return null;
    }

}


